package com.medusa.aps.business.modules.board.model.input;

import com.medusa.aps.business.global.model.exception.GlobalException;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.medusa.aps.business.model.constant.RegexPool.REGEX_DAY_HOUR_MINUTE_SECOND;

/**
 * 时间formatter
 * @author An.Yan
 */
@Data
public class DurationFormatter {

    @Min(value = 0)
    @Max(value = 9999999999L)
    private final Integer days;

    @Min(value = 0)
    @Max(value = 24)
    private final Integer hours;

    @Min(value = 0)
    @Max(value = 60)
    private final Integer minutes;

    @Min(value = 0)
    @Max(value = 60)
    private final Integer seconds;

    public DurationFormatter (Integer days, Integer hours, Integer minutes, Integer seconds) {
        this.days = days;
        this.hours = hours;
        this.minutes = minutes;
        this.seconds = seconds;
    }

    public DurationFormatter(String processingTimeStr) {
        if (!processingTimeStr.matches(REGEX_DAY_HOUR_MINUTE_SECOND)) {
            throw new GlobalException("加工时间格式不正确");
        }
        String regex = "(\\d+)";
        Pattern r = Pattern.compile(regex);
        Matcher m = r.matcher(processingTimeStr);
        List<Integer> digitalList = new ArrayList<>();
        while (m.find()) {
            digitalList.add(Integer.valueOf(m.group()));
        }
        if (digitalList.size() != 4) {
            throw new GlobalException("加工时间格式不正确");
        }

        this.days = digitalList.get(0);
        this.hours = digitalList.get(1);
        this.minutes = digitalList.get(2);
        this.seconds = digitalList.get(3);
    }

    public Integer calculateSeconds() {
        return this.days * 86400 + this.hours * 3600 + this.minutes * 60 + this.seconds;
    }
    public DurationFormatter(Long time) {
        this(Integer.parseInt(String.valueOf(TimeUnit.SECONDS.toDays(time))),
                Integer.parseInt(String.valueOf(TimeUnit.SECONDS.toHours(time) - TimeUnit.DAYS.toHours(TimeUnit.SECONDS.toDays(time)))),
                Integer.parseInt(String.valueOf(TimeUnit.SECONDS.toMinutes(time) - TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(time)))),
                Integer.parseInt(String.valueOf(TimeUnit.SECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(time)))));
    }


}
